﻿using Client.EditDialog;
using Client.HttpHelp;
using Client.ICommandNotify;
using Client.Models;
using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;

namespace Client.ViewModel.Equip
{
    public class EquipViewModel : NotifyBase
    {
        public EquipViewModel()
        {
            Selectcommand = new Command(ReverseDoExecute, ReverseCanExecute);
            EditCommand = new Command(EditDoExecute, EditCanExecute);
        }




        #region 方法
        private bool EditCanExecute()
        {
            return !string.IsNullOrWhiteSpace(DocumentNumber);
        }
        private bool ReverseCanExecute()
        {
            return !string.IsNullOrWhiteSpace(DocumentNumber);
        }

        private async void ReverseDoExecute(object obj)
        {
            var Http_ = HelpTools.IOC.Getobject<Http>();
            Models.Http.ParameterModel parameterModel = new Models.Http.ParameterModel();
            Http_.Uir = "http://cpms_equip.scrbg.com/json.rpc";
            var Dialog_ = HelpTools.IOC.Getobject<MessageDialog.Dialog>();
            var DbContext_ = HelpTools.IOC.Getobject<SqlServer.DbContext>();
            //单据反写
            if ((obj as string) == "1")
            {
                string strconfig = HelpTools.IOC.Getobject<IConfiguration.IConfigurationHelp>().GetSetUpModel().Where(o => o.DatabaseName == Title)?.FirstOrDefault()?.ConnectingString;
                if (string.IsNullOrWhiteSpace(strconfig))
                {
                    Dialog_.OpenMessage("数据连接字符串为空,请检查数据库配置是否正确");
                    return;
                }
                DbContext_.SqlConfigstr = strconfig;
                Dialog_.OpenDialog = true;
                await Task.Delay(2000);
                var selctsata = await Task.Run(() =>
                {
                    return DbContext_.Where($"SELECT a.BillId, a.WorkId FROM {SelectText} a WHERE BillNo='{DocumentNumber}'").Select().Select(o =>
                    {
                        return new
                        {
                            BillId = o["BillId"].ToString(),
                            WorkId = o["WorkId"].ToString(),
                        };
                    }).FirstOrDefault();
                });
                if (string.IsNullOrWhiteSpace(selctsata?.BillId) || string.IsNullOrWhiteSpace(selctsata?.WorkId))
                {
                    Dialog_.OpenDialog = false;
                    Dialog_.OpenMessage("没有查询到单据数据");
                    return;
                }
                parameterModel.@params = new
                {
                    Id = selctsata.BillId,
                    State = 2,
                    workId = selctsata.WorkId,
                    pass = true
                };
                parameterModel.method = $"SettleEquip.{SelectText.Split("_")[1]}.AuditAfter";
                ResponseData = await Http_.PostData(parameterModel, "", "application/json");
                Dialog_.OpenDialog = false;
                return;
            }
            if ((obj as string) == "2")
            {
                QueryCMB();
                return;
            }
            if ((obj as string) == "3")
            {
                QueryZLYS();
                return;
            }
            if ((obj as string) == "4")
            {
                AuditAfterZLYS();
            }
            if ((obj as string) == "5")
            {
                EasShareAudit();
            }
        }
        //处理财务退回
        private async void EasShareAudit()
        {
            if (string.IsNullOrWhiteSpace(SelectText)||string.IsNullOrWhiteSpace(Opinion) || string.IsNullOrWhiteSpace(DocumentNumber))
            {
                WPFDevelopers.Minimal.Controls.MessageBox.Show("类型/意见必填", "消息", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            };
            var Http_ = HelpTools.IOC.Getobject<Http>();
            Models.Http.ParameterModel parameterModel = new Models.Http.ParameterModel();
            Http_.Uir = "http://192.168.91.112:7074/json.rpc";
            parameterModel.method = "SettleEquip.WorkFlowService.EasShareAudit";
            parameterModel.@params = new
            {
                BillType = SelectText,
                BillId= DocumentNumber ,
                IsPass=false ,
                Opinion= Opinion
            };
            var Dialog_ = HelpTools.IOC.Getobject<MessageDialog.Dialog>();
            Dialog_.OpenDialog = true;
            ResponseData = await Http_.PostData(Newtonsoft.Json.JsonConvert.SerializeObject(parameterModel),"", "application/json");
            Dialog_.OpenDialog = false;
        }

        /// <summary>
        /// 编辑
        /// </summary>
        /// <param name="obj"></param>
        private void EditDoExecute(object obj)
        {
            var data = obj as Models.CBM_EquipmentLeaseList;
            if (data == null) return;
            DialogWindow dialogWindow = new DialogWindow(data, o =>
            {
                var o1 = (o as Models.CBM_EquipmentLeaseList);
                data.SettledAmount = o1.SettledAmount;
                data.OrderQty = o1.OrderQty;
            },
            new EditDialog.CBM_EquipmentLeaseList());
            dialogWindow.ShowDialog();
        }
        /// <summary>
        /// 查询合同
        /// </summary>
        private async void QueryCMB()
        {
            var DbContext_ = HelpTools.IOC.Getobject<SqlServer.DbContext>();
            var Dialog_ = HelpTools.IOC.Getobject<MessageDialog.Dialog>();
            string strconfig = HelpTools.IOC.Getobject<IConfiguration.IConfigurationHelp>().GetSetUpModel().Where(o => o.DatabaseName == Title)?.FirstOrDefault()?.ConnectingString;
            if (string.IsNullOrWhiteSpace(strconfig))
            {
                Dialog_.OpenMessage("数据连接字符串为空,请检查数据库配置是否正确");
                return;
            }
            DbContext_.SqlConfigstr = strconfig;
            Dialog_.OpenDialog = true;
            CBM_EquipmentLeaseList = await Task.Run(() =>
            {
                var data = DbContext_.Where($"SELECT a.ContractId  FROM Settle_Zljs a WHERE BillNo='{DocumentNumber}'").Select().Select(o =>
                  {
                      return new
                      {
                          ContractId = o["ContractId"].ToString()
                      };
                  }).FirstOrDefault();
                if (string.IsNullOrWhiteSpace(data?.ContractId))
                {
                    return new List<Models.CBM_EquipmentLeaseList>();
                }
                DbContext_.SqlConfigstr = "Data Source=192.168.100.6;Initial Catalog=SRBG_CBM;User ID=sa;Password=asdw@122";
                return DbContext_.Where<Models.CBM_EquipmentLeaseList>($"SELECT a.ItemName,a.Size,a.Unit,a.Qty,a.Price,a.Amount,a.SettledAmount,a.OrderQty  FROM CBM_EquipmentLeaseList a WHERE BillId= '{data.ContractId}' ");
            });
            Dialog_.OpenDialog = false;
        }
        /// <summary>
        /// 查询租赁验收
        /// </summary>
        /// <exception cref="NotImplementedException"></exception>
        private async void QueryZLYS()
        {
            var DbContext_ = HelpTools.IOC.Getobject<SqlServer.DbContext>();
            var Dialog_ = HelpTools.IOC.Getobject<MessageDialog.Dialog>();
            string strconfig = HelpTools.IOC.Getobject<IConfiguration.IConfigurationHelp>().GetSetUpModel().Where(o => o.DatabaseName == Title)?.FirstOrDefault()?.ConnectingString;
            if (string.IsNullOrWhiteSpace(strconfig))
            {
                Dialog_.OpenMessage("数据连接字符串为空,请检查数据库配置是否正确");
                return;
            }
            DbContext_.SqlConfigstr = strconfig;
            Dialog_.OpenDialog = true;
            ZLYS_EquipmentLeaseList = await Task.Run(() =>
            {
                var data = DbContext_.Where($"SELECT a.BillNo,a.BillId,a.AgreementId FROM  Equip_LeaseAcceptance a WHERE BillNo ='{DocumentNumber}'").Select().Select(o =>
                {
                    return new
                    {
                        ContractId = o["AgreementId"].ToString(),
                        BillId = o["BillId"].ToString()
                    };
                }).FirstOrDefault();
                var dtl = DbContext_.Where($"SELECT a.EquipName,a.SpecificationModel,a.Unit,a.ContractDtlId FROM Equip_LeaseAcceptanceDtl a WHERE a.BillId = '{data?.BillId}'").Select().Select(o =>
                {
                    return new
                    {
                        EquipName = o["EquipName"].ToString(),
                        SpecificationModel = o["SpecificationModel"].ToString(),
                        Unit = o["Unit"].ToString(),
                        ContractDtlId = o["ContractDtlId"].ToString()
                    };
                });
                var Ljdtl = DbContext_.Where($"SELECT b.ContractDtlId FROM [dbo].[Equip_LeaseAcceptanceDtl] b JOIN Equip_LeaseAcceptance a on a.BillId=b.BillId WHERE a.AgreementId='{data?.ContractId}' And b.ContractDtlId in({string.Join(",", dtl.Select(t => t.ContractDtlId).Distinct().Select(o => $"'{o}'"))}) AND a.Status=2").Select().Select(o =>
                {
                    return new
                    {
                        ContractDtlId = o["ContractDtlId"].ToString()
                    };
                });
                //查询合同
                DbContext_.SqlConfigstr = "Data Source=192.168.100.6;Initial Catalog=SRBG_CBM;User ID=sa;Password=asdw@122";
                var CBMlist = DbContext_.Where($"SELECT a.DtlId,a.Qty,a.CheckQty FROM CBM_EquipmentLeaseList a WHERE BillId = '{data?.ContractId}' ").Select().Select(o =>
                {
                    return new
                    {
                        DtlId = o["DtlId"].ToString(),
                        Qty = o["Qty"].ToString(),
                        CheckQty = o["CheckQty"].ToString()
                    };
                });

                if (string.IsNullOrWhiteSpace(data?.ContractId))
                {
                    return new List<ZLYSModel>();
                }
                List<ZLYSModel> listdata = new List<ZLYSModel>();
                foreach (var item in dtl)
                {
                    if (!listdata.Where(o => o.Id == item.ContractDtlId).Any())
                    {
                        var da = CBMlist.FirstOrDefault(y => y.DtlId == item.ContractDtlId);
                        listdata.Add(new ZLYSModel()
                        {
                            Id = item.ContractDtlId,
                            ItemName = item.EquipName,
                            Unit = item.Unit,
                            SpecificationModel = item.SpecificationModel,
                            EqQty = dtl.Where(o => o.ContractDtlId == item.ContractDtlId).Count().ToString(),
                            YsQty = Ljdtl.Where(o => o.ContractDtlId == item.ContractDtlId).Count().ToString(),
                            Qty = da?.Qty,
                            CheckQty = da?.CheckQty
                        });
                    }

                }
                return listdata;
            });
            Dialog_.OpenDialog = false;
        }
        /// <summary>
        /// 租赁验收处理成以审核
        /// </summary>
        private async void AuditAfterZLYS()
        {
            var Http_ = HelpTools.IOC.Getobject<Http>();
            var Dialog_ = HelpTools.IOC.Getobject<MessageDialog.Dialog>();
            var DbContext_ = HelpTools.IOC.Getobject<SqlServer.DbContext>();
            Models.Http.ParameterModel parameterModel = new Models.Http.ParameterModel();
            parameterModel.method = "Equip.Flow.CommitTest";
            parameterModel.@params = new
            {
                BillType = 4,
                Id = DocumentNumber
            };
            Http_.Uir = "http://192.168.91.112:7074/json.rpc";
            Dialog_.OpenDialog = true;
            string strconfig = HelpTools.IOC.Getobject<IConfiguration.IConfigurationHelp>().GetSetUpModel().Where(o => o.DatabaseName == Title)?.FirstOrDefault()?.ConnectingString;
            if (string.IsNullOrWhiteSpace(strconfig))
            {
                Dialog_.OpenMessage("数据连接字符串为空,请检查数据库配置是否正确");
                return;
            }
            DbContext_.SqlConfigstr = strconfig;
            string strresp = await Http_.PostData(parameterModel, "", "application/json");
            if (strresp.Contains("error"))
            {
                ResponseData = strresp;
                return;
            }
            ResponseData = await Task.Run(() =>
            {
                var data = DbContext_.Where($"SELECT a.BillId, a.WorkId FROM Equip_LeasePlan a WHERE BillId='{DocumentNumber}'").Select().Select(o =>
                 {
                     return new
                     {
                         BillId = o["BillId"].ToString(),
                         WorkId = o["WorkId"].ToString(),
                     };
                 }).FirstOrDefault();
                if (data == null || string.IsNullOrWhiteSpace(data.WorkId)) return "处理失败,流程ID不存在 请手动处理";
                DbContext_.SqlConfigstr = "Data Source=192.168.100.150;Initial Catalog=SRBG_FlowEngin;User ID=sa;Password=sclq@pcwp1.0";//选择流程数据库
                var TaskList = DbContext_.Where("SELECT A.DISPID, C.UNITNAME, A.USERNAME, B.TASKID, A.STATE " +
                    "FROM USERDISP A WITH(NOLOCK) INNER JOIN TASK B WITH(NOLOCK) ON A.TASKID = B.TASKID " +
                    "INNER JOIN UNIT C WITH(NOLOCK) ON B.UNITID = C.UNITID  " +
                    "INNER JOIN WORK D WITH(NOLOCK) ON B.WORKID = D.WORKID  " +
                    "LEFT JOIN TASKORDER E ON B.TASKID = E.NEXTTASKID " +
                    "WHERE D.STATE <> 2 AND " +
                    $"D.WORKID = '{data.WorkId}' ORDER BY E.PRIORTASKID").Select().Select(o =>
                    {
                        return new
                        {
                            DISPID = o["DISPID"].ToString(),
                            UNITNAME = o["UNITNAME"].ToString(),
                            USERNAME = o["USERNAME"].ToString(),
                            TASKID = o["TASKID"].ToString(),
                            STATE = int.Parse(o["STATE"].ToString())
                        };
                    });
                if (TaskList.Last().STATE != 2 && TaskList.Last().UNITNAME == "业务财务接收")
                {
                    DbContext_.Update($"update WORK set STATE = 1 where WORKID = '{data.WorkId}'");
                    DbContext_.Update($"update USERDISP set STATE = 2,FINISHTIME = GETDATE(),ISPASS = 1  where DISPID = '{TaskList.Last().DISPID}'");
                    DbContext_.Update($"update TASK set STATE = 2,FINISHTIME = GETDATE()  where TASKID = '{TaskList.Last().TASKID}'");
                }
                return "处理成功";
            });
            Dialog_.OpenDialog = false;
        }
        #endregion

        #region 命令
        public Command Selectcommand { get; set; }
        /// <summary>
        /// 租赁合同编辑
        /// </summary>
        public Command EditCommand { get; set; }
        #endregion
        #region 属性
        private string Title_ = "设备";
        //标题
        public string Title
        {
            get { return Title_; }
            set { Title_ = value; }
        }
        private string Opinion_;
        //意见
        public string Opinion
        {
            get { return Opinion_; }
            set { Opinion_ = value; }
        }

        private string DocumentNumber_;
        //单据编号
        public string DocumentNumber
        {
            get { return DocumentNumber_; }
            set { DocumentNumber_ = value; }
        }
        private string ResponseData_;
        //HTTP请求响应数据
        public string ResponseData
        {
            get { return ResponseData_; }
            set
            {
                ResponseData_ = value;
                SetProperty(ref DocumentNumber_, DocumentNumber);
            }
        }
        private Dictionary<string, string> DocumentType_;
        /// <summary>
        /// 单据类型选择
        /// </summary>
        public Dictionary<string, string> DocumentType
        {
            get
            {
                if (DocumentType_ == null || DocumentType_.Count == 0)
                {
                    DocumentType_ = new Dictionary<string, string>();
                    var IConfigurationHelp_ = HelpTools.IOC.Getobject<IConfiguration.IConfigurationHelp>();
                    foreach (var item in IConfigurationHelp_.GetSetUpTableModel().Where(t => t.ModuleName == Title_))
                    {
                        DocumentType_.Add(item.TableValue, item.TableName);
                    }
                    return DocumentType_;
                }
                else
                {
                    return DocumentType_;
                }
            }
            set { DocumentType_ = value; }
        }
        private Dictionary<string,string> EasTypeList_;

        public Dictionary<string,string> EasTypeList
        {
            get {
                   if (EasTypeList_ == null || EasTypeList_.Count == 0)
                {
                    EasTypeList_ = new Dictionary<string, string>();
                    EasTypeList_.Add("EquipSettle_Cgjs", "采购结算");
                    EasTypeList_.Add("EquipSettle_Zlyjs", "租赁预结算");
                    EasTypeList_.Add("EquipSettle_Zljs", "租赁结算");
                    EasTypeList_.Add("EquipSettle_Wxjs", "维修结算");
                    EasTypeList_.Add("EquipSettle_Yshtjs", "运输合同结算");
                    EasTypeList_.Add("EquipSettle_Sbxsjs", "设备销售结算");
                    EasTypeList_.Add("EquipSettle_Sbfjczjs", "设备废旧处置结算");
                    EasTypeList_.Add("EquipSettle_Sbzlsrjs", "设备租赁收入结算");
                    EasTypeList_.Add("EquipSettle_Qtsrjs", "其他收入结算");
                    EasTypeList_.Add("Settle_Transfer", "设备调动结算");
                    return EasTypeList_;
                }
                else
                {
                    return EasTypeList_;
                }
            }
            set { EasTypeList_ = value; }
        }


        private string SelectText_;
        /// <summary>
        /// 选中的类型数据
        /// </summary>
        public string SelectText
        {
            get { return SelectText_; }
            set { SelectText_ = value; }
        }
        /// <summary>
        /// 设备租赁合同
        /// </summary>
        private List<Models.CBM_EquipmentLeaseList> CBM_EquipmentLeaseList_=new List<Models.CBM_EquipmentLeaseList>();

        public List<Models.CBM_EquipmentLeaseList> CBM_EquipmentLeaseList
        {
            get { return CBM_EquipmentLeaseList_; }
            set { CBM_EquipmentLeaseList_ = value;
                SetProperty(ref CBM_EquipmentLeaseList_, CBM_EquipmentLeaseList);
            }
        }
        /// <summary>
        /// 设备租赁验收
        /// </summary>
        private List<ZLYSModel> ZLYS_EquipmentLeaseList_ = new List<ZLYSModel>();

        public List<ZLYSModel> ZLYS_EquipmentLeaseList
        {
            get { return ZLYS_EquipmentLeaseList_; }
            set
            {
                ZLYS_EquipmentLeaseList_ = value;
                SetProperty(ref ZLYS_EquipmentLeaseList_, ZLYS_EquipmentLeaseList);
            }
        }
        #endregion
    }
}
